package org.pupil.rpc.protocol.serialization.serializationImpl;

import org.pupil.rpc.protocol.serialization.RpcSerialization;
import org.pupil.rpc.protocol.serialization.SerializationException;

import java.io.*;

/**
 * jdk字节流 序列化
 */
public class JdkSerialization implements RpcSerialization {

    @Override
    public <T> byte[] serialize(T object) {
        if (object == null) {
            throw new NullPointerException();
        }

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
            return outputStream.toByteArray();
        } catch (Exception e) {
            throw new SerializationException("序列化失败", e);
        }
    }


    @SuppressWarnings("unchecked") //告诉编译器忽略与类型转换相关的未检查警告
    @Override
    public <T> T deSerialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null) {
            throw new NullPointerException();
        }

        try{
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            return (T) objectInputStream.readObject();
        } catch (Exception e) {
            throw new SerializationException("反序列化失败", e);
        }
    }
}
